<?php
class login extends Controller {
	public function __construct()
	{
		parent::Controller();
		$this->load->model(array('usuarios','mresponsable','mkey','uscontrolusuariomodel','mdepartamento'));
		 $this->load->helper('cookie');
	}

	function index()
	{
		   // $this->checkKey();
			if ($this->session->userdata('LOGGED_USR_ID') > 0) {
			 	redirect('main');
		    }   
			$this->load->view('login');	
	}
	
	function logout()
	{
		$this->session->sess_destroy();
		header('location: '.base_url()); 
	}

	function ulogin()
	{
		$error  = '';
		$this->form_validation->set_rules('username', '"Nombre de Usuario"', 'trim|required');
		$this->form_validation->set_rules('upassword', '"Contrase&ntilde;a"', 'trim|required');
		
		if ($this->form_validation->run())
		{
		    
			$usr = $this->usuarios->Login($this->input->post('username'), $this->input->post('upassword'));
			if($usr !== false) {
				
				$res_obj=$this->mresponsable->LoadEstatusById($usr->getIdresponsable());
				$responsable=$res_obj->getNombre();
				
				$deparment = $this->mdepartamento->LoadEstatusById($usr->getIdDepartamento());
				$depa = $deparment->getNombre();
				
				$this->session->set_userdata('LOGGED_USR_ID', $usr->getIdUsuario());
				$this->session->set_userdata('LOGGED_USR_NAME', $usr->getUsernameUsuario());
				$this->session->set_userdata('LOGGED_NAME', $usr->getNombreUsuario());
				$this->session->set_userdata('LOGGED_USR_Responsable',$usr->getIdresponsable());
				$this->session->set_userdata('LOGGED_RESPONSABLE',$responsable);
				$this->session->set_userdata('LOGGED_ROL',$usr->getIdRol());
				$this->session->set_userdata('LOGGED_DEPAR_Nombre',$depa);
				$this->session->set_userdata('LOGGED_DEPAR',$usr->getIdDepartamento());
				
			    $dataControlUs = array("fecha"       => date('Y-m-d H:i:s'),
				                       "id_usuario"  => $usr->getIdUsuario());
				
				$this->uscontrolusuariomodel->addRegistro($dataControlUs);
				
				if ($usr->getIdresponsable() == 3) {

					redirect('main');

					redirect('graficoseguimientosventas');
					
				}else if($usr->getIdresponsable() == 5){
					redirect('transaccionentrada/mainEmail');
				}
				
				if ($usr->getIdDepartamento() == 6) {
					redirect('CompanyEntrega');
				}
		
				redirect('main');
			} 
			else 
			{
				$error = 'El nombre de usuario y/o la contrase&ntilde;a son incorrectos';
			}
		}

		$this->load->view('login',array('error' => $error));
	}
	
	public function checkKey()
	{
	  $key = $this->mkey->loadById();
	   
	  $cookie = get_cookie('adminc24h');
	   
	  if ($key->getDescriccion() != $cookie) {
	  	redirect('http://company24h.com');
	  }
	  
	}
}